package com.gking.processHarvest.controller;


import com.gking.processHarvest.common.BaseContext;
import com.gking.processHarvest.common.Res;
import com.gking.processHarvest.service.ChatHistory.ChatHistoryService;
import com.gking.processHarvest.utils.SseServer;
import com.gking.processHarvest.utils.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;


@Slf4j
@RestController
public class ChatHistoryController {

    @Autowired
    private ChatHistoryService chatHistoryService;


    /**
     * 推送数据给特定用户
     *
     * @param targetId 目标id
     * @param message  消息
     * @return s
     */
    @ResponseBody
    @PostMapping("/websocket/push")
    public Res<String> pushToTarget(@RequestParam("targetId") String targetId, @RequestParam("message") String message) {
        log.warn("targetId ： {} ，  message： {} ", targetId, message);

        try {
            String decodedString = URLDecoder.decode(message, StandardCharsets.UTF_8.toString());
            String subString = decodedString.substring(0, decodedString.length() - 1);
            log.warn("message的详情是: {}", message);
            log.warn("message UTF-8的详情是: {}", decodedString);

            WebSocketServer.sendMessageTo(targetId, subString);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return Res.success("success");
    }


    /**
     * 群发消息
     *
     * @param message 消息
     * @return d
     */
    @ResponseBody
    @PostMapping("/websocket/push/public")
    public Res<String> pushMessage(@RequestBody String message) {
        try {
            String decodedString = URLDecoder.decode(message, StandardCharsets.UTF_8.toString());
            String subString = decodedString.substring(0, decodedString.length() - 1);
            log.warn("message的详情是: {}", message);
            log.warn("message UTF-8的详情是: {}", decodedString);

            WebSocketServer.sendInfo(subString);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return Res.success("success");
    }


    /**
     * 连接 enduring sse
     *
     * @param response 响应
     */
    @CrossOrigin
    @GetMapping(value = "/sse/enduring/connect", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter connectEnduringSSE(HttpServletResponse response) {
        log.warn("userId 为： {}", BaseContext.getCurrentId());
        response.setContentType("text/event-stream");
        response.setCharacterEncoding("utf-8");

        return SseServer.enduringConnectSSE(BaseContext.getCurrentId());
    }


    /**
     * 连接 chatting sse
     *
     * @param response 响应
     */
    @CrossOrigin
    @GetMapping(value = "/sse/chatting/connect", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter connectChattingSSE(HttpServletResponse response) {
        log.warn("userId 为： {}", BaseContext.getCurrentId());
        response.setContentType("text/event-stream");
        response.setCharacterEncoding("utf-8");

        return SseServer.chattingConnectSSE(BaseContext.getCurrentId());
    }


    /**
     * 获取未读消息数量
     */
    @GetMapping("/sse/notRead/count")
    public Res<String> getNotReadMessageCount() {
        boolean b = chatHistoryService.refreshNotReadCount(BaseContext.getCurrentId());
        if (b) return Res.success("获取未读消息数量成功！");
        else return Res.error("获取未读消息数量失败！");
    }


    /**
     * 给特定用户发消息
     *
     * @param receiverId 指定用户id
     * @return s
     */
    @PostMapping("/sse/chatting/send/{receiverId}")
    public Res<String> sendChattingMessage(@PathVariable String receiverId, @RequestBody String message) {
        log.warn("接收消息者 id 为 {}, 消息详情为： {}", receiverId, message);
        try {
            String decodedString = URLDecoder.decode(message, StandardCharsets.UTF_8.toString());
            String subString = decodedString.substring(0, decodedString.length() - 1);
            log.warn("message的详情是: {}", message);
            log.warn("message UTF-8的详情是: {}", decodedString);

            return chatHistoryService.sendChattingMessage(receiverId, subString);

        } catch (IOException e) {
            e.printStackTrace();
            return Res.error("发送消息失败！");
        }
    }


    /**
     * 检查  发送未接收到的消息，存在则发送消息
     *
     * @return s
     */
    @GetMapping("/sse/chatting/notReceive")
    public Res<String> checkChattingNotReceiveMessage() {
        return chatHistoryService.checkChattingNotReceiveMessage();
    }


}
